package com.atguigu.aspect;

import com.atguigu.annotations.TestIdempotent;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class TestIdempotentAspect {

    @Resource
    private RedisTemplate redisTemplate;

    @Around("@annotation(com.atguigu.annotations.TestIdempotent)")
    public Object IdempotentAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        //redisKey
        String idemKey = "idempotent:";

        //获取方法签名
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();

        //通过方法签名获取方法
        Method method = signature.getMethod();

        TestIdempotent annotation = method.getAnnotation(TestIdempotent.class);

        //存在注解
        if (!ObjectUtils.isEmpty(annotation)) {
            //获取redis中的是否存在幂等值
            String idem = (String) redisTemplate.opsForValue().get(idemKey);
            if (idem == null) {
                //代表第一次访问添加幂等值
                redisTemplate.opsForValue().set(idemKey, "processed", 60L, TimeUnit.SECONDS);
                System.out.println("添加幂等判断成功");
                return proceedingJoinPoint.proceed();
            }else {//非第一次访问提示重复提交
                System.out.println("重复提交");
                return false;
            }
        }else {//不存在注解直接放行
             return proceedingJoinPoint.proceed();
        }
    }
}
